#include<bits/stdc++.h>
using namespace std;
#include<map>
#include<queue>
#include<algorithm>
#define int long long
using namespace std;
const int dx[] = {-1, 0, 0, 1}, dy[] = {0, -1, 1, 0};
int n;
signed main()
{
	cin >> n;
	queue<int> q;
	q.push(n);
	map<int, int> m;
	m[n] = 0;
	while (!q.empty()) {
		int u = q.front();
		int c[3][3], f = 0, g = 0, n = u ;
		q.pop();
		if (u == 123804765) {
			break;
		}
		for (int i = 2; i >= 0; i--) {
			for (int j = 2; j >= 0; j--) {
				//存入3x3数组
				c[i][j] = n % 10, n /= 10;
				if (!c[i][j]) {
					f = i, g = j;// 记录空格
				}
			}
		}
		for (int i = 0; i < 4; i++) {
			int nx = f + dx[i], ny = g + dy[i], ns = 0;
			if (nx < 0 || ny < 0 || nx > 2 || ny > 2) {
				continue;
			}
			swap(c[nx][ny], c[f][g]);// 尝试交换
			for (int i = 0; i < 3; i++) {
				for (int j = 0; j < 3; j++) {
					ns = ns * 10 + c[i][j];// 变成9位数
				}
			}
			if (!m.count(ns)) {
				m[ns] = m[u] + 1;// 放进maxp
				q.push(ns);// 插入队列
			}
			swap(c[nx][ny], c[f][g]);// 交换 当前和空格的位置
		}
	}// 循环 直到 等到123804765 map搜索出来
	cout << m[123804765] << endl;
	return 0;
}
